import functools
import re
import sys

import requests


def mycmp1(x,y):  #升序排列
    return x["cues"][0]["time"]-y["cues"][0]["time"]

def mycmp2(x,y):  #升序排列
    return x["time"]-y["time"]

def mycmp3(x,y):  #升序排列
    return x[0]-y[0]

def down_load_translate(name,diff=0):
    en_url = f"https://www.ted.com/talks/{name}/transcript.json?language=en"
    cn_url = f"https://www.ted.com/talks/{name}/transcript.json?language=zh-cn"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
                      "(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
    }
    en_res = requests.get(en_url, headers=headers)
    cn_res = requests.get(cn_url, headers=headers)

    en_paragraphs = en_res.json()["paragraphs"]
    en_paragraphs.sort(key = functools.cmp_to_key(mycmp1))
    cn_paragraphs = cn_res.json()["paragraphs"]
    cn_paragraphs.sort(key = functools.cmp_to_key(mycmp1))

    en_list = []
    for en_p in en_paragraphs:
        cues_list = en_p["cues"]
        for c in cues_list:
            en_list.append(c)
    en_list.sort(key=functools.cmp_to_key(mycmp2))

    cn_list = []
    for cn_p in cn_paragraphs:
        cues_list = cn_p["cues"]
        for c in cues_list:
            cn_list.append(c)
    cn_list.sort(key=functools.cmp_to_key(mycmp2))

    if len(en_list) != len(cn_list):
        return

    time_cn_dict = {}
    time_list = []

    for e  in  en_list:
        e["time"] = e["time"]+int(diff)

    for i in range(len(en_list)):
        en_cue = en_list[i]
        cn_cue = cn_list[i]
        time_cn_dict[en_cue["time"]] = cn_cue["text"]
        end = 0
        if i== (len(en_list)-1):
            end = en_cue["time"]+10000
        else:
            end = en_list[i+1]["time"]-20

        tup = (en_cue["time"],end,en_cue["text"].replace("\n","") ,cn_cue["text"].replace("\n",""))
        time_list.append(tup)
    time_list.sort(key=functools.cmp_to_key(mycmp3))

    # print(time_list)

    for i in range(len(en_paragraphs)):
        cues_en = en_paragraphs[i]["cues"]
        cues_en.sort(key=functools.cmp_to_key(mycmp2))
        for j in range(len(cues_en)):
            text_ = cues_en[j]["text"].replace("\n","")
            print(text_,end=' ')
        print("")

        for j in range(len(cues_en)):
            text_ = time_cn_dict[cues_en[j]["time"]]
            text_ = text_.replace("\n","")
            print(text_,end=' ')
        print("")

    srt = []
    srt_en = []
    srt_cn = []

    for i in range(len(time_list)):
        t = time_list[i]
        fs, fms = divmod(t[0], 1000)
        fm, fs = divmod(fs, 60)
        fh, fm = divmod(fm, 60)
        start = "{}:{}:{},{}".format(str(int(fh)).zfill(2), str(int(fm)).zfill(2), str(int(fs)).zfill(2),
                                     str(int(fms)).zfill(3))
        es, ems = divmod(t[1], 1000)
        em, es = divmod(es, 60)
        eh, em = divmod(em, 60)
        end = "{}:{}:{},{}".format(str(int(eh)).zfill(2), str(int(em)).zfill(2), str(int(es)).zfill(2),
                                   str(int(ems)).zfill(3))
        srt_tmp = f"""{i+1}\n{start} --> {end}\n{t[2]}\n{t[3]}\n"""
        srt_tmp_en = f"""{i+1}\n{start} --> {end}\n{t[2]}\n"""
        srt_tmp_cn = f"""{i+1}\n{start} --> {end}\n{t[3]}\n"""
        srt.append(srt_tmp)
        srt_en.append(srt_tmp_en)
        srt_cn.append(srt_tmp_cn)

    with open(f"/Users/xinyu.jiang/Desktop/tmp/{name}-en-cn.srt", "w", encoding="utf-8") as f:
        f.write("\n".join(srt))
    with open(f"/Users/xinyu.jiang/Desktop/tmp/{name}-en.srt", "w", encoding="utf-8") as f:
        f.write("\n".join(srt_en))
    with open(f"/Users/xinyu.jiang/Desktop/tmp/{name}-cn.srt", "w", encoding="utf-8") as f:
        f.write("\n".join(srt_cn))


if __name__ == "__main__":
    arg1 = "derek_sivers_keep_your_goals_to_yourself"
    arg2 = 0
    down_load_translate(arg1,arg2)
